﻿using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace 模拟豆包悬浮
{
    public partial class MainWindow : Window
    {
        private Point mouseOffset;
        private DispatcherTimer autoHideTimer;
        private ToolTip toolTip;
        private bool isBeingDragged = false;
        private Point dragStartPosition;
        private WindowState previousWindowState;

        public MainWindow()
        {
            InitializeComponent();
            //InitializeDragAndDrop();
            InitializeToolTip();

            // 启用组合渲染以减少闪烁
            RenderOptions.SetBitmapScalingMode(this, BitmapScalingMode.HighQuality);
            RenderOptions.SetEdgeMode(this, EdgeMode.Aliased);
        }

        private void InitializeDragAndDrop()
        {
            AssistantBall.MouseLeftButtonDown += (sender, e) =>
            {
                if (e.ClickCount == 2)
                {
                    // 双击事件处理（如果需要）
                    return;
                }

                dragStartPosition = e.GetPosition(null);
                mouseOffset = e.GetPosition(this);
                AssistantBall.CaptureMouse();
                isBeingDragged = true;
                previousWindowState = WindowState;

                // 提升Z轴以确保拖动时在最上层
                Panel.SetZIndex(this, 100);

                // 添加按下时的视觉反馈
                AssistantBall.Fill = (SolidColorBrush)new BrushConverter().ConvertFromString("#0E42D2");

                // 禁用工具提示
                if (toolTip != null)
                {
                    toolTip.IsOpen = false;
                }

                // 启用平滑拖动
                this.UseLayoutRounding = true;
                this.SnapsToDevicePixels = true;
            };

            AssistantBall.MouseMove += (sender, e) =>
            {
                if (isBeingDragged && e.LeftButton == MouseButtonState.Pressed)
                {
                    Point currentPosition = e.GetPosition(null);

                    // 计算位移增量
                    double deltaX = currentPosition.X - dragStartPosition.X;
                    double deltaY = currentPosition.Y - dragStartPosition.Y;

                    // 只有当位移超过最小阈值时才移动窗口，减少微小移动
                    if (Math.Abs(deltaX) > 2 || Math.Abs(deltaY) > 2)
                    {
                        // 使用双缓冲技术减少闪烁
                        this.Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(() =>
                        {
                            Left += deltaX;
                            Top += deltaY;

                            // 更新拖动起始位置
                            dragStartPosition = currentPosition;
                        }));
                    }
                }
            };

            AssistantBall.MouseLeftButtonUp += (sender, e) =>
            {
                AssistantBall.ReleaseMouseCapture();
                isBeingDragged = false;

                // 恢复Z轴
                Panel.SetZIndex(this, 0);

                // 恢复原始颜色
                AssistantBall.Fill = (SolidColorBrush)new BrushConverter().ConvertFromString("#165DFF");

                // 恢复窗口状态
                WindowState = previousWindowState;

                // 重置布局设置
                this.UseLayoutRounding = false;
                this.SnapsToDevicePixels = false;
            };
        }

        private void InitializeToolTip()
        {
            autoHideTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(3)
            };
            autoHideTimer.Tick += (sender, e) => HideToolTip();

            AssistantBall.MouseEnter += (sender, e) =>
            {
                if (!isBeingDragged)
                {
                    ShowToolTip();
                }
            };

            AssistantBall.MouseLeave += (sender, e) =>
            {
                if (!isBeingDragged && toolTip != null && !toolTip.IsMouseOver)
                {
                    autoHideTimer.Start();
                }
            };
        }

        private void ShowToolTip()
        {
            autoHideTimer.Stop();

            if (toolTip == null)
            {
                toolTip = new ToolTip
                {
                    Content = "有问题找我哦～",
                    Background = Brushes.White,
                    BorderBrush = Brushes.Gray,
                    BorderThickness = new Thickness(1),
                    //CornerRadius = new CornerRadius(5),
                    Padding = new Thickness(8, 5, 8, 5),
                    FontSize = 12,
                    Effect = new DropShadowEffect
                    {
                        BlurRadius = 5,
                        Color = Colors.Black,
                        Direction = 315,
                        ShadowDepth = 1
                    },
                    PlacementTarget = AssistantBall,
                    Placement = PlacementMode.Bottom,
                    VerticalOffset = 10
                };

                // 为ToolTip添加事件处理
                toolTip.MouseEnter += (sender, e) => autoHideTimer.Stop();
                toolTip.MouseLeave += (sender, e) => autoHideTimer.Start();
            }

            toolTip.IsOpen = true;

            // 淡入动画
            var fadeInAnimation = new DoubleAnimation
            {
                From = 0,
                To = 1,
                Duration = TimeSpan.FromSeconds(0.3)
            };
            toolTip.BeginAnimation(OpacityProperty, fadeInAnimation);
        }

        private void HideToolTip()
        {
            if (toolTip != null)
            {
                // 淡出动画
                var fadeOutAnimation = new DoubleAnimation
                {
                    From = 1,
                    To = 0,
                    Duration = TimeSpan.FromSeconds(0.3)
                };

                fadeOutAnimation.Completed += (sender, e) =>
                {
                    toolTip.IsOpen = false;
                };

                toolTip.BeginAnimation(OpacityProperty, fadeOutAnimation);
            }
        }

        private void AssistantBall_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                this.DragMove();
            }
        }
    }
}
